#include "rpc_utils.h"
#include <rdtsc.h>

uint64_t RPCUtils::gen_uuid()
{
    tsc_counter uuid;
    RDTSC(uuid);
    return (uint64_t)uuid.int64;
}

int32_t RPCUtils::zip_compress( std::string & compress_data, const std::string & source_data )
{
    int32_t ret = Z_OK;
    uint64_t source_len =  source_data.length();
    uint64_t compress_len = 12 + uint64_t(source_len * 1.5f);
    unsigned char * compress = new unsigned char[compress_len];
    if( NULL == compress )
        return -1;
    ret = ::compress( compress, &compress_len, (const unsigned char*)source_data.c_str(), source_len );
    if( Z_OK == ret )
        compress_data.assign( (const char*)compress, compress_len );
    delete[] compress;
    return ( Z_OK == ret ? 0 : -1 );
}

int32_t RPCUtils::zip_uncompress( std::string & source_data, int32_t before_compress_len,
    const std::string & compress_data )
{
    int32_t ret = Z_OK;
    unsigned char * source = new unsigned char[before_compress_len];
    if( NULL == source )
        return -1;
    uint64_t source_len = 0;
    ret = ::uncompress( source, &source_len, (const unsigned char*)compress_data.c_str(),
        (uint64_t)compress_data.length() );
    if( (int32_t)source_len != before_compress_len )
    {
        delete[] source;
        return -1;
    }
    if( Z_OK == ret )
        source_data.assign( (char*)source, source_len );
    delete[] source;
    return ( Z_OK == ret ? 0 : -1 );
}

uint64_t RPCUtils::calc_crc( const char * data, size_t data_len )
{
    uint64_t adler  = adler32( 0, NULL, 0 );
    return adler32( adler, (const unsigned char*)data, data_len );
}

int32_t RPCUtils::round_up( int32_t size, int32_t up2size )
{
	if( 0 == size )
		return 0;
		
	return ( size + (  up2size - 1 ) ) & ~( up2size - 1 );
}

